const mockTarget = import.meta.env.VITE_MOCK_TARGET;
let tokenValid = true;

/**
 * 响应成功拦截器，2xx范围内的状态码都会触发该函数。不能使用箭头函数，否则无this
 * @param axiosResponse {
 *   status: 来自服务器响应的HTTP状态码
 *   statusText: 来自服务器响应的HTTP状态信息
 *   data: 由服务器提供的响应
 *   headers: 服务器响应头。header名都是小写，而且可以使用方括号语法访问，例如`response.headers['content-type']`
 *   config: axios的请求配置信息
 *   httpClientV2: 生成此响应的请求。Nodejs中为最后一个ClientRequest实例，浏览器中为XMLHttpRequest实例
 * }
 * @returns {Promise<never>|Promise<unknown>}
 */
const handleResponseFulfilled = function handleResponseFulfilled(axiosResponse) {
  const reqConfig = axiosResponse.config;
  const serverResponse = axiosResponse.data;
  
  // 请求响应完毕关闭loading
  if (reqConfig.loading) {
    reqConfig.hideLoading();
  }
  
  // 文件下载
  if (serverResponse instanceof Blob) {
    return Promise.resolve(axiosResponse);
  }
  
  // 响应体构建
  const data = reqConfig.completeResponse ? axiosResponse : serverResponse;
  
  // 非json数据
  const contentType = axiosResponse.headers['content-type'];
  if (!contentType.includes('application/json')) {
    return Promise.resolve(data);
  }
  
  // 判断业务是否成功
  let isBusinessSuccess = false;
  // 如果url被mock，则业务成功
  if (reqConfig.url.includes(mockTarget)) {
    isBusinessSuccess = true;
  }
  // 响应状态码等于成功响应状态码，则业务成功
  if (serverResponse.code === reqConfig.responseBusinessCode.success) {
    isBusinessSuccess = true;
  }
  
  const msg = serverResponse.msg;
  
  // 业务不成功
  if (!isBusinessSuccess) {
    if (reqConfig.showFailureMsg && tokenValid) { // tokenValid表示只提示一次token失效
      reqConfig.showFailureMsgFunction(msg);
    }
    
    // token失效
    if (
      serverResponse.code === reqConfig.responseBusinessCode.tokenTimeout ||
      serverResponse.code === reqConfig.responseBusinessCode.tokenInvalid ||
      serverResponse.code === reqConfig.responseBusinessCode.tokenNotFound
    ) {
      tokenValid = false;
      
      this.options.handleTokenInvalid();
    }
    return Promise.reject(data);
  }
  
  // 业务成功
  tokenValid = true;
  if (reqConfig.showSuccessMsg) {
    reqConfig.showSuccessMsgFunction(msg);
  }
  
  return Promise.resolve(data);
};

export default handleResponseFulfilled;
